package com.github.llyb120.performance.define;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;

public class Helper {

    public final static ThreadLocal<LinkedList> localElement = new ThreadLocal<LinkedList>(){
        @Override
        protected LinkedList initialValue() {
            return new LinkedList();
        }
    };
    private final static Map<String, List<Callback>> callbackMap = new ConcurrentHashMap<>();

    //拦截器
    final static List<Interceptor> interceptors = new CopyOnWriteArrayList<>();

    public enum EventType{
        PRE,
        POST
        ;
    }

    public interface Callback{
        void call(Context context);
    }

//    public static void Emit(EventType type, String path, Context stack){
//        String key = buildKey(type, path);
//        List<Callback> list = callbackMap.get(key);
//        if (list == null) {
//            return;
//        }
//        for (Callback callback : list) {
//            callback.call(stack);
//        }
//    }

    public static void AddInterceptor(Interceptor instance){
        interceptors.add(instance);
//        for (Method method : instance.getClass().getDeclaredMethods()) {
//            if(method.getParameterTypes().length == 1 && method.getParameterTypes()[0] == Context.class){
//                Visit listen = method.getAnnotation(Visit.class);
//                if (listen == null) {
//                    continue;
//                }
//                Listen(listen.type(), listen.path(), c -> {
//                    try {
//                        method.invoke(instance, c);
//                    } catch (IllegalAccessException | InvocationTargetException e) {
//                        throw new RuntimeException(e);
//                    }
//                });
//            }
//        }
    }

//    public static void Listen(String path, Callback callback){
//        Listen(EventType.POST, path, callback);
//    }
//
//    public static void Listen(EventType type, String path, Callback callback){
//        String key = buildKey(type, path);
//        List<Callback> list = null;
//        synchronized (callbackMap){
//            list = callbackMap.get(key);
//            if (list == null) {
//                list = new ArrayList<>();
//                callbackMap.put(key, list);
//            }
//        }
//        list = callbackMap.get(key);
//        list.add(callback);
//    }
//    private static String buildKey(EventType type, String path){
//        return String.format("$%s$%s", type.name(), path);
//    }


    public static void ClearElements(){
        localElement.get().clear();
    }
    public static List GetElements(){
        return (List) localElement.get();
    }
}
